package org.icdio.servlet;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Connection;
import java.util.Date;
import java.sql.PreparedStatement;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.websocket.Session;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.icdio.utils.DBUtils;

import net.sf.json.JSONObject;

/**
 * Servlet implementation class FileUpload
 */
@WebServlet("/FileUpload")
public class FileUpload extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public FileUpload() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		System.out.println("进入后台");
		String fName = "";
		String suffix = "";
		String urlString = "";
		DiskFileItemFactory factory = new DiskFileItemFactory();
		String path = "d:\\fileUpload";
		//				this.getServletContext().getRealPath("/upload");
		factory.setRepository(new File(path));
		factory.setSizeThreshold(1024*1024*1024);
		ServletFileUpload upload = new ServletFileUpload(factory);
		Session session 
		try {
			List<FileItem> list = (List<FileItem>) upload.parseRequest(request);
			for(FileItem item:list){
				String name = item.getString();
				if(item.isFormField()){
					String value = item.getString();
					request.setAttribute(name, value);
				}else {
					String value = item.getName();
					int start = value.lastIndexOf("\\");
					String filename = value.substring(start + 1);
					if(filename.indexOf(".")>=0){
						int indexdot = filename.indexOf(".");
						suffix = filename.substring(indexdot);
						fName = filename.substring(0,filename.lastIndexOf("."));;
						Date nowTime = (Date) new java.util.Date();
						fName =fName + "_" + nowTime.getTime();
						fName = fName + suffix;
						urlString = "http://localhost:8080/fileUpload/"+fName;
					}
					File picFileDir = new File(path);
					if(!picFileDir.exists()){
						picFileDir.mkdir();
					}
					File file = new File(path,fName);
					OutputStream out = new FileOutputStream(file);
					request.setAttribute(name, fName);
					InputStream in = item.getInputStream();
					int length = 0; 
					byte[] buf = new byte[1024];
					System.out.println("获取上次文件的总共的容量"+item.getSize());
					while ((length = in.read(buf))!=-1) {
						out.write(buf,0,length);	
					}
					JSONObject jsonObject = new JSONObject();
					saveUrl(urlString, fName, item.getSize(), suffix);
					System.out.println(urlString.toString());
					in.close();
					out.close();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}
	
	/**
	 * 文件中转
	 * @param urlString
	 * 2018年8月11日下午2:23:06
	 * name:官江涛
	 */
	protected void saveUrl (String urlString,String fileName, long size, String suffix) {
		Connection conn = null;
		try {
			conn = DBUtils.open();
			String sql = "UPDATE picurl SET Url = ?, fileName = ? , size = ?,type = ? where id = 1";
			PreparedStatement stmt = conn.prepareStatement(sql);
			stmt.setString(1, urlString);
			stmt.setString(2, fileName);
			stmt.setLong(3, size);
			stmt.setString(4, suffix.substring(1));
			stmt.executeUpdate();	
			System.out.println("上传成功！");
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			DBUtils.close(conn);
		} 		
	}

}
